<script setup>
import { ref } from 'vue'
import api from '@/api'
import { parsePage, parseQuery } from '@/utils'
import { useRoute, useRouter } from 'vue-router'
import { Modal } from '@arco-design/web-vue'
import watchModal from './watchModal.vue'

const $route = useRoute()
const $router = useRouter()

const listFormData = ref({
  page: parsePage($route.query.page, 1),
  department_id: $route.query.department_id || '',
  keyword: $route.query.keyword || '',
  'post_ids[]': [],
})
const listData = ref([])
const listTotal = ref(0)
const listLoading = ref(false)

const getListData = async (page = 1) => {
  listLoading.value = true
  try {
    listFormData.value.page = page
    const query = parseQuery(listFormData.value)
    $router.replace({ query })
    const res = await api.get('users', {
      params: query,
    })
    listData.value = res.data.items
    listTotal.value = res.data.pageInfo.total
  } catch (error) {
    console.error(error)
  }
  listLoading.value = false
}

const resetListData = () => {
  listFormData.value.keyword = ''
  listFormData.value.department_id = ''
  listFormData.value['post_ids[]'] = []
  getListData()
}

getListData()

const formRef = ref()
const formItem = ref()
const formLoading = ref(false)
const formVisible = ref(false)
const formData = ref({
  name: '',
  username: '',
  password: '',
  post_ids: [],
})
const formRules = {
  name: [
    {
      required: true,
      message: '请填写名字',
    },
  ],
  username: [
    {
      required: true,
      message: '请填写手机号',
    },
  ],
}

const create = () => {
  formRef.value?.resetFields()
  formItem.value = null
  formVisible.value = true
}

const update = (item) => {
  formRef.value?.resetFields()
  formItem.value = item
  formData.value.name = item.name
  formData.value.username = item.username
  formData.value.password = ''
  formData.value.post_ids = item.posts.map((item) => item.id)
  formVisible.value = true
}

const formSubmit = async () => {
  if (await formRef.value.validate()) {
    return false
  }

  formLoading.value = true

  try {
    if (formItem.value) {
      await api.put('users/' + formItem.value.id, formData.value)
    } else {
      await api.post('users', formData.value)
    }
    formRef.value?.resetFields()
    formVisible.value = false
    getListData()
  } catch (error) {
    console.error(error)
  }

  formLoading.value = false

  return false
}

const del = (item) => {
  Modal.confirm({
    title: '删除员工',
    content: '您确定要删除吗？',
    bodyStyle: 'text-align:center',
    onBeforeOk: async () => {
      await api.delete('users/' + item.id)

      getListData()
    },
  })
}

const posts = ref([])
const postsLoading = ref(false)
const getPostOptions = async () => {
  postsLoading.value = true
  try {
    const res = await api.get('posts/options')
    posts.value = res.data
  } catch (error) {
    console.error(error)
  }
  postsLoading.value = false
}
getPostOptions()

const watchModalRef = ref()
</script>

<template>
  <div class="page">
    <div class="header">
      <a-space>
        <a-button type="primary" @click="create">添加员工</a-button>
      </a-space>
      <a-form
        :model="listFormData"
        class="page-form"
        layout="inline"
        @submit="getListData()"
      >
        <a-space>
          <a-select
            v-model="listFormData.department_id"
            placeholder="所属部门"
            allow-clear
            allow-search
            :loading="postsLoading"
            @change="listFormData['post_ids[]'] = []"
          >
            <a-option v-for="(item,index) of posts" :key="index" :value="item.id">
              {{ item.name }}
            </a-option>
          </a-select>

          <a-select
            placeholder="所属岗位"
            allow-clear
            multiple
            v-model="listFormData['post_ids[]']"
            :max-tag-count="1"
          >
            <template v-for="(group,index) in posts" :key="index">
              <a-optgroup
                :label="group.name"
                v-if="
                  !listFormData.department_id ||
                  group.id == listFormData.department_id
                "
              >
                <a-option :value="item.id" v-for="(item,indexs) in group.posts" :key="indexs">
                  {{ item.name }}
                </a-option>
              </a-optgroup>
            </template>
          </a-select>

          <a-input
            v-model.trim="listFormData.keyword"
            placeholder="账号、手机号、姓名"
            allow-clear
          />

          <a-button type="primary" html-type="submit">
            <template #icon><icon-search /></template>
            查询
          </a-button>

          <a-button @click="resetListData">
            <template #icon><icon-refresh /></template>重置
          </a-button>
        </a-space>
      </a-form>
    </div>

    <a-table
      :loading="listLoading"
      @page-change="getListData"
      class="table"
      :data="listData"
      :pagination="{
        simple: true,
        showTotal: true,
        size: 'small',
        total: listTotal,
        pageSize: 20,
        current: listFormData.page,
      }"
    >
      <template #columns>
        <a-table-column title="序号" :width="60">
          <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
        </a-table-column>
        <a-table-column title="姓名" data-index="name"></a-table-column>
        <a-table-column
          title="账号/手机号"
          data-index="username"
        ></a-table-column>
        <a-table-column title="部门岗位">
          <template #cell="{ record }">
            <a-space>
              <a-tag bordered color="gray" v-for="(post,index) in record.postsall" :key="index">
                {{ post.department.name }}({{ post.name }})
              </a-tag>
            </a-space>
          </template>
        </a-table-column>
        <a-table-column
          title="加入时间"
          data-index="created_at"
        ></a-table-column>
        <a-table-column align="right" :width="88">
          <template #cell="{ record }">
            <a-space>
              <a-button
                type="primary"
                size="mini"
                @click="watchModalRef.show(record)"
              >
                观看记录
              </a-button>
              <a-button type="primary" size="mini" @click="update(record)">
                编辑
              </a-button>
              <a-button
                type="primary"
                status="danger"
                size="mini"
                @click="del(record)"
              >
                删除
              </a-button>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <a-modal
      v-model:visible="formVisible"
      :title="(formItem ? '编辑' : '添加') + '员工'"
      width="800px"
      :ok-loading="formLoading"
      :on-before-ok="formSubmit"
    >
      <a-form ref="formRef" :model="formData" :rules="formRules">
        <a-form-item field="name" label="姓名">
          <a-input v-model="formData.name" allow-clear />
        </a-form-item>
        <a-form-item field="username" label="账号/手机号">
          <a-input v-model="formData.username" allow-clear />
        </a-form-item>
        <a-form-item field="post_ids" label="岗位">
          <a-select multiple v-model="formData.post_ids">
            <a-optgroup :label="group.name" v-for="(group,index) in posts" :key="index">
              <a-option :value="item.id" v-for="(item,indexs) in group.posts" :key="indexs">
                {{ item.name }}
              </a-option>
            </a-optgroup>
          </a-select>
        </a-form-item>
        <a-form-item
          field="password"
          label="密码"
          :rules="formItem ? [] : [{ required: true, message: '请填写密码' }]"
        >
          <a-input-password v-model="formData.password" allow-clear />
        </a-form-item>
      </a-form>
    </a-modal>

    <watchModal ref="watchModalRef"></watchModal>
  </div>
</template>

<style scoped></style>
